import { useState, useMemo, useEffect } from 'react';
import { Input } from 'antd';
import style from './style.module.scss';
import type { StoreInfo } from '@/Interface/StoreInfoInterface';
import http from '@/api/axios';
import { debounce } from '@/utils/debounce';

type BaseStoreSearchProps = {
  /** 选择门店后的回调（参数为选中的门店） */
  onSelect: (store: StoreInfo) => void;
  /** 额外的操作按钮（可选） */
  extraButtons?: React.ReactNode;
};

const BaseStoreSearch = ({ onSelect, extraButtons }: BaseStoreSearchProps) => {
  const [searchText, setSearchText] = useState('');
  const [showDropdown, setShowDropdown] = useState(false);
  const [mockStores, setMockStores] = useState<StoreInfo[] | null>(null);

  // 加载门店数据（公共逻辑）
  useEffect(() => {
    const getData = async () => {
      try {
        const res = await http.get('/api/storesData');
        setMockStores(res.data.data);
      } catch (error) {
        console.error('初始化数据失败:', error);
      }
    };
    getData();
  }, []);

  // 搜索过滤（公共逻辑）
  const matchedStores = useMemo(() => {
    if (!searchText.trim()) return [];
    const lowerText = searchText.toLowerCase();
    return mockStores?.filter(store =>
      store.basicInfo.storeName.toLowerCase().includes(lowerText) ||
      store.basicInfo.storeId.includes(searchText)
    ).slice(0, 3) || [];
  }, [searchText, mockStores]);

  // 防抖处理（公共逻辑）
  const debouncedSearch = useMemo(
    () => debounce((value: string) => setShowDropdown(!!value), 300),
    []
  );

  // 生命周期清理（公共逻辑）
  useEffect(() => {
    return () => debouncedSearch.cancel?.();
  }, [debouncedSearch]);

  return (
    <div className={style.input}>
      {/* 输入框 */}
      <Input
        placeholder="输入门店名称或ID"
        allowClear
        value={searchText}
        onChange={(e) => {
          setSearchText(e.target.value);
          debouncedSearch(e.target.value);
        }}
        onFocus={() => setShowDropdown(!!searchText)}
        onBlur={() => setTimeout(() => setShowDropdown(false), 200)}
      />

      {/* 下拉结果 */}
      {showDropdown && matchedStores.length > 0 && (
        <div className={style.dropdown}>
          {matchedStores.map(store => (
            <div
              key={store.basicInfo.storeId}
              className={style.item}
              onClick={() => {
                setSearchText(store.basicInfo.storeName);
                setShowDropdown(false);
                onSelect(store); // 触发外部回调
              }}
            >
              <div className={style.name}>{store.basicInfo.storeName}</div>
              <div className={style.id}>{store.basicInfo.storeId}</div>
            </div>
          ))}
        </div>
      )}

      {/* 额外操作按钮 */}
      {extraButtons && <div className={style.btn}>{extraButtons}</div>}
    </div>
  );
};

export default BaseStoreSearch;